package com.hbsx.filters.pre;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 前置过滤器 配置完成后要在ZuulApplication中将它注入Spring Bean容器
 */
public class ThirdPreFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 3;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文获取logic-is-success,用于判断此Filter是否执行
        return (boolean) ctx.get("logic-is-success");
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("*******************ThirdPreFilter已执行*******************");
        //从RequestContext获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文获取HttpServletRequest
        HttpServletRequest request = ctx.getRequest();
        //从request常识获取参数a
        String b = request.getParameter("b");
        if (null == b){
            //对该请求禁止路由，也就是禁止访问下游服务
            ctx.setSendZuulResponse(false);
            //设定responseBody供PostFilter
            ctx.setResponseBody("{\"status\":500,\"message\":\"参数b不能为空!\"}");
            //logic-is-success保存于上下文，作为同类型下游Filter的执行开关
            ctx.set("logic-is-success",false);
            //到此Filter逻辑结束
            return null;
        }
        return null;
    }
}
